'use strict'

import { dbConfig, seqIncetanceObj } from "./db";
import { Sequelize } from 'sequelize';

class dbInstance {

    private sequelizeInstance: seqIncetanceObj;
    static instance: dbInstance

    constructor() {
        this.sequelizeInstance = {}
    }

    static getInstance() {
        if (!dbInstance.instance) {
            dbInstance.instance = new dbInstance();
        }
        return dbInstance.instance;
    }
    // get seq instance
    getSequelizeInstance(dbInfo: dbConfig) {
        if (!dbInfo.database || !dbInfo.host || !dbInfo.port) {
            console.log('缺少database或者host');
            return false;
        }
        const seqKey: string = '' + dbInfo.database + dbInfo.host + dbInfo.port;
        // @ts-ignore
        if (this.sequelizeInstance[seqKey]) return this.sequelizeInstance[seqKey];
        if (!dbInfo.user || !dbInfo.password) {
            console.log('缺少dbAccount或者dbPassword');
            return false;
        }
        //@ts-ignore
        this.sequelizeInstance[seqKey] = new Sequelize(dbInfo.database, dbInfo.user, dbInfo.password, {
            host: dbInfo.host,
            dialect: 'mysql',
            port: dbInfo.port,
            timezone: "+08:00",
            // logging: false
            query: { raw: true }
        });
        // @ts-ignore
        return this.sequelizeInstance[seqKey];
    }

}

export default dbInstance.getInstance();
